package com.qq.dao;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qq.pojo.User;
import com.qq.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author： Aeolia
 * @Description： TODO
 * @Date： 2021/10/16 22:23
 */
public class UserDao {

    public User findUserByAccountAndPassword(String account, String password) {
        String sql = "select * from user where account = ? and password = ?";
        Connection connection = null;
        try {
            connection = JDBCUtils.getConnection();
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, account);
            statement.setString(2, password);

            ResultSet resultSet = statement.executeQuery();
            User user = new User();
            if (resultSet.isBeforeFirst()) {
                while (resultSet.next()) {
                    user.account = resultSet.getString("account");
                    user.password = resultSet.getString("password");
                    user.name = resultSet.getString("name");
                    String friendsList = resultSet.getString("friends");
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        ArrayList list = mapper.readValue(friendsList, ArrayList.class);
                        user.friendsList = list;
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
                return user;
            }else{
                return null;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

}
